package com.younio.local.util;

import java.net.NetworkInterface;
import java.util.Enumeration;

public final class HardWareUtils {

    public static String getDefaultMac() {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface ni = interfaces.nextElement();

                byte[] mac = ni.getHardwareAddress();
                if (mac != null) {
                    return getMac(mac);
                }

            }
        } catch (Exception e) {
            return "error";
        }

        return "";
    }

    private static String getMac(byte[] mac) {
        if (mac == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < mac.length; i++) {
            if (i != 0) {
                sb.append("-");
            }
            String s = Integer.toHexString(mac[i] & 0xFF);
            sb.append(s.length() == 1 ? 0 + s : s);
        }

        return sb.toString().toUpperCase();
    }
}
